package com.goldsprite.infinityworld.entities.components;

import com.goldsprite.utils.math.Vector2;

import com.badlogic.gdx.graphics.OrthographicCamera;
import com.goldsprite.gdxcore.entities.AnimatorEntity;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.scenes.scene2d.ui.Touchpad;

public class FollowCameraContoller{
	private Touchpad rocker;
	private OrthographicCamera transCam;
	private AnimatorEntity role;
	
	public boolean enableFollowCam = true, enableFollowCamScl = true;
	public Vector2 worldSize = new Vector2();
	
	public float followSpeed = 2.4f;
	
	
	public FollowCameraContoller(OrthographicCamera transCam, Touchpad rocker, AnimatorEntity role, float followSpeed){
		this.transCam = transCam;
		this.rocker = rocker;
		this.role = role;
		this.followSpeed = followSpeed;
	}
	
	public void update(float delta){
		if(enableFollowCam) followCam(role, followSpeed);
	}
	
	//相机跟随
	Vector2 forward = new Vector2();
	private void followCam(AnimatorEntity role, float lerpRate){
		//目标位置
		Vector2 roleCenter = role.getCenterPosition();
		float offset = 20;
		float perX = rocker.getKnobPercentX();
		float perY = rocker.getKnobPercentY();

		//TODO 这里vec2会infinity, 需要手动修正一下
		forward.set(perX, perY);
		//forward.normalize();
		if(!Float.isFinite(forward.x))forward.x=0;
		if(!Float.isFinite(forward.y))forward.y=0;
		forward.scl(offset);
		Vector2 targetPosition = new Vector2(roleCenter).add(forward.x, forward.y);
		//LogViewerService.logDebug(""+targetPosition);
		//pause = true;

		//目标视野大小
		float targetZoom = role.getBodySize().y * 5.5f / getWorldSize().y;//2倍 5.5f*0.5f
		Vector2 transCamPos = new Vector2(transCam.position.x, transCam.position.y).add(getWorldSize().x / 2, getWorldSize().y / 2);

		//位移
		Vector2 lerp = Vector2.lerp(transCamPos, targetPosition, lerpRate * 1 / 60f);
		transCamPos.set(lerp);
		transCam.position.set(transCamPos.x - getWorldSize().x / 2, transCamPos.y - getWorldSize().y / 2, 0);
		//缩放
		if(enableFollowCamScl){
			float zoom = MathUtils.lerp(transCam.zoom, targetZoom, lerpRate * 1.5f * 1 / 60f);
			transCam.zoom = zoom;
		}
	}
	
	public Vector2 getWorldSize(){
		return worldSize.set(transCam.viewportWidth, transCam.viewportHeight);
	}
	
}
